package com.onadake.web.service;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.onadake.utils.ValidationUtils;
import com.onadake.web.dao.RequestService;

/**
 * Implementation of human verification service which is using are you a human interface.
 * 
 * @author radek.hecl
 *
 */
@Service
public class AYAHHumanVerificationService implements HumanVerificationService {

    /**
     * Builder object.
     */
    public static class Builder {

        /**
         * Whether service is enabled or not. If disabled, then every verification request will pass successfully (will return true).
         */
        private Boolean enabled;

        /**
         * Service for making remote requests.
         */
        private RequestService requestService;

        /**
         * Sets whether this service is enabled or not.
         * If disabled, then every verification request will pass successfully (will return true).
         * 
         * @param enabled whether this service is enabled or not
         * @return this instance
         */
        public Builder setEnabled(boolean enabled) {
            this.enabled = enabled;
            return this;
        }

        /**
         * Sets service for making remote requests.
         * 
         * @param requestService service for making remote requests
         * @return this instance
         */
        public Builder setRequestService(RequestService requestService) {
            this.requestService = requestService;
            return this;
        }
        
        /**
         * Builds the result object.
         * 
         * @return created object
         */
        public AYAHHumanVerificationService build() {
            return new AYAHHumanVerificationService(this);
        }
    }

    /**
     * Whether service is enabled or not. If disables, then every verification request will pass successfully (will return true).
     */
    @Value("${ui.humanVerificationEnabled}")
    private Boolean enabled;

    /**
     * Service for making remote requests.
     */
    @Autowired
    private RequestService requestService;
    
    /**
     * Constructor to allow frameworks create new instances.
     */
    @SuppressWarnings("unused")
    private AYAHHumanVerificationService() {
    }

    /**
     * Creates new instance.
     * 
     * @param builder builder object
     */
    public AYAHHumanVerificationService(Builder builder) {
        enabled = builder.enabled;
        requestService = builder.requestService;
        guardInvariants();
    }

    /**
     * Guards this object to be consistent. Throws exception if this is not the case.
     */
    @PostConstruct
    private void guardInvariants() {
        ValidationUtils.guardNotNull(enabled, "enabled cannot be null");
        ValidationUtils.guardNotNull(requestService, "requestService cannot be null");
    }

    @Override
    public boolean isHuman(String token) {
        if (!enabled.booleanValue()) {
            return true;
        }

        try {
            String data = "session_secret=" + token + "&" + "scoring_key=b9cf7a9360594ed548b70d36630e898499bf8fc2";
            String res = requestService.request("https://ws.areyouahuman.com/ws/scoreGame", data);
            JSONTokener tokener = new JSONTokener(res);
            JSONObject jobj = new JSONObject(tokener);
            int status_code = ((Number) jobj.get("status_code")).intValue();
            return (status_code == 1) ? true : false;
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
    
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}
